package com.cn.jinl.service;


import com.cn.jinl.api.IBoxManageService;
import com.cn.jinl.api.IProductStorageRelateService;
import com.cn.jinl.dao.*;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@EnableScheduling
@Service
public class BoxManageServiceImpl implements IBoxManageService  {

    @Autowired
    private BoxManageMapper boxManageMapper;

    @Autowired
    private ProductStorageRelateMapper productStorageRelateMapper;
    @Autowired
    private PlanManageMapper planManageMapper;
    @Autowired
    private ProductStorageMapper productStorageMapper;
    @Autowired
    private ProductStorageOutRelateMapper productStorageOutRelateMapper;


    @Autowired
    private OnDutyProductMapper onDutyProductMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private PlanOrderMapper planOrderMapper;

    @Autowired
    private OrderBackInfoMapper orderBackInfoMapper;
    @Autowired
    private ProductStorageOutMapper productStorageOutMapper;
    @Autowired
    private OrderOutInfoMapper orderOutInfoMapper;
    @Autowired
    private OrderOutRelateMapper orderOutRelateMapper;
    @Autowired
    private GenerateUUID generateUUID;

    @Autowired
    private RedisTemplate redisTemplate;

    public static Object locked = new Object();

    @Override
    public List<BoxManage> getBoxManageList(QueryForm queryForm) throws Exception {
        int count = boxManageMapper.selectBoxManageListCount(queryForm);
        if (count == 0) {
            return Lists.newArrayList();
        }
        List<BoxManage> boxManages = boxManageMapper.selectBoxManageList(queryForm);
        boxManages.get(0).setCount(count);
        return boxManages;
    }

    @Override
    public String addBoxManage(BoxManage boxManage) throws Exception {
        List<BoxManage> addBoxes = Lists.newArrayList();
        String year = generateUUID.getYearTwoStr();
        BoxManageExample example = new BoxManageExample();
        String tempCode = year + "000001";
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andBoxCodeEqualTo(tempCode);
        int existCount = boxManageMapper.countByExample(example);
        if (existCount > 0) {
            return "今年的箱码已经存在！";
        }
        for (int i = 1; i < 1000000; i++) {
            BoxManage add = new BoxManage();
            String code = year + generateUUID.getSixNumStr(i);
            add.setBoxCode(code);
            addBoxes.add(add);
        }

        //分批次插入
        int startIndex = 0;
        int batchIndex = 1000;
        for (int i = 0; i < batchIndex; i++) {
            if (startIndex >= addBoxes.size()) {
                break;
            }
            List<BoxManage> subList = addBoxes.subList(startIndex, (i + 1) * batchIndex - 1);
            boxManageMapper.batchInsertBoxManage(subList);
            startIndex = (i + 1) * batchIndex;
        }
        return "";
    }

    @Override
    public String updateBoxManage(List<BoxManage> boxManages) throws Exception {
        if (CollectionUtils.isEmpty(boxManages)) {
            return "参数异常！";
        }
        int count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateBatchRepeatPrintBox(BoxManage boxManage) throws Exception {
        String boxCode = boxManage.getBoxCode();
        if (StringUtils.isEmpty(boxCode)) {
            return "箱码区间值不能为空!";
        }
        int range = Integer.parseInt(boxCode);
        if (range <= 0) {
            return "箱码区间值不能小于1!";
        }
        if (range > 1000) {
            return "箱码区间值不大于1000!";
        }
        synchronized (locked){
            BoxManageExample example = new BoxManageExample();
            example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPrintTimeIsNull();
            example.setOrderByClause("box_code asc");
            List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
            List<BoxManage> otherBoxCodes = Lists.newArrayList();
            if (boxManages.size() < range) {
                BoxManageExample example1 = new BoxManageExample();
                example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPrintTimeIsNotNull().andPrintCodeEqualTo("0");
                example1.setOrderByClause("box_code asc");
                otherBoxCodes = boxManageMapper.selectByExample(example1);
                int disValue = range - boxManages.size();
                disValue = otherBoxCodes.size() > disValue ? disValue : otherBoxCodes.size();
                otherBoxCodes.subList(0, disValue);
                boxManages.addAll(otherBoxCodes);
            }else{
                boxManages =  boxManages.subList(0, range);
            }

            List<String> boxCodes = Lists.newArrayList();
            for (BoxManage box : boxManages) {
                boxCodes.add(box.getBoxCode());
            }
            BoxManage update = new BoxManage();
            update.setPrintTime(boxManage.getPrintTime());
            update.setPrintUserName(boxManage.getPrintUserName());
            redisTemplate.opsForList().leftPushAll("boxs", boxCodes);
            redisTemplate.expire("boxs", 60, TimeUnit.SECONDS);
            for (int i = 0; i < 4; i++) {
                int startIndex = i * 500;
                int endIndex = i * 500 + 500;
                endIndex = endIndex > boxCodes.size() ? boxCodes.size() : endIndex;
                if (startIndex >= endIndex) {
                    break;
                }
                BoxManageExample example2 = new BoxManageExample();
                List<String> updateCodes = boxCodes.subList(startIndex, endIndex);
                example2.createCriteria().andBoxCodeIn(updateCodes);
                int count = boxManageMapper.updateByExampleSelective(update, example2);
                if (count < 0) {
                    throw new Exception("更新表异常!");
                }
            }
        }
        return "";
    }

    @Override
    public String updateBatchRepeatPrintBox1(BoxManage boxManage) throws Exception {
        String boxCode = boxManage.getBoxCode();
        if (StringUtils.isEmpty(boxCode)) {
            return "箱码区间值不能为空!";
        }
        int range = Integer.parseInt(boxCode);
        if (range <= 0) {
            return "箱码区间值不能小于1!";
        }
        if (range >= 2000) {
            return "箱码区间值小于2000!";
        }
        BoxManageExample example1 = new BoxManageExample();
        example1.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andPrintTimeIsNotNull().andPrintCodeEqualTo("0");
        example1.setOrderByClause("box_code asc");
        List<BoxManage>  otherBoxCodes = boxManageMapper.selectByExample(example1);
        long size = redisTemplate.opsForList().size("hasPrintCodes");
        List<String> codes = redisTemplate.opsForList().range("hasPrintCodes",0,size -1);
        List<String> boxCodes = Lists.newArrayList();
        for(BoxManage box : otherBoxCodes){
            if(!codes.contains(box.getBoxCode())){
                if(boxCodes.size() == range){
                    break;
                }
                boxCodes.add(box.getBoxCode());
            }
        }
        redisTemplate.opsForList().leftPushAll("hasPrintCodes",boxCodes);
        redisTemplate.opsForList().leftPushAll("boxs", boxCodes);
        redisTemplate.expire("boxs", 60, TimeUnit.SECONDS);
        return "";
    }

    @Override
    public String scanBoxInfo(String boxCode,String itemTypeId,String gradeValue) throws Exception {
        if (StringUtils.isEmpty(boxCode)) {
            return "0";//箱码为空
        }
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andBoxCodeEqualTo(boxCode);
        List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(boxManages)) {
            return "1";//规格不对，扫码失败
        }
        if (boxManages.size() != 1) {
            return "2！";//箱码存在重复
        }

        BoxManage exist = boxManages.get(0);
        if (StringUtils.equals(exist.getCodeStatus(), "0")) {
            return "3";//箱码未入库
        }
        //未报工 入库
        ProductStorageRelateExample productStorageRelateExample = new ProductStorageRelateExample();
        productStorageRelateExample.createCriteria().andBoxCodeEqualTo(boxCode).andLockedEqualTo(Constants.NORMAL_STATUS);
        List<ProductStorageRelate> productStorageRelates = productStorageRelateMapper.selectByExample(productStorageRelateExample);
        //出库
        ProductStorageOutRelateExample productStorageOutRelateExample = new ProductStorageOutRelateExample();
        productStorageOutRelateExample.createCriteria().andBoxCodeEqualTo(boxCode);
        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectByExample(productStorageOutRelateExample);
        if (productStorageRelates.size() == 0 && productStorageOutRelates.size() == 0) {
            return "4";//箱码已入库但未出库
        }
        if (productStorageOutRelates.size() >0 ) {
            return "6";//箱码已出库
        }
        //判断出库的规格品类箱码是否存在在报工的数据中
        ProductStorageRelateExample productStorageRelateExample1 = new ProductStorageRelateExample();
        productStorageRelateExample1.createCriteria().andBoxCodeEqualTo(boxCode).andLockedEqualTo(Constants.NORMAL_STATUS).andItemTypeIdEqualTo(itemTypeId).andGradeValueEqualTo(gradeValue);
        List<ProductStorageRelate> productStorageRelateList = productStorageRelateMapper.selectByExample(productStorageRelateExample1);
        if (productStorageRelateList.size() == 0 ) {
            return "5";//品类规格箱码匹配不上报工的数据
        }
        return "";
    }

    @Override
    public String scanTuiHuoBoxInfo(String boxCode) throws Exception {
        if (StringUtils.isEmpty(boxCode)) {
            return "箱码为空！";
        }
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andBoxCodeEqualTo(boxCode);
        List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(boxManages)) {
            return "规格不对，扫码失败";
        }
        if (boxManages.size() != 1) {
            return "箱码存在重复！";
        }

        BoxManage exist = boxManages.get(0);
        if (StringUtils.equals(exist.getPrintCode(), "0")) {
            return "箱码未使用";
        }
        return "";
    }

    @Override
    public String updateEmptyPrintBox(List<BoxManage> boxManages) throws Exception {
        if (CollectionUtils.isEmpty(boxManages)) {
            return "参数不能为空！";
        }
        List<String> boxCodes = Lists.newArrayList();
        for (BoxManage boxManage : boxManages) {
            boxCodes.add(boxManage.getBoxCode());
        }
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andBoxCodeIn(boxCodes);
        List<BoxManage> exists = boxManageMapper.selectByExample(example);
        List<String> boxes = Lists.newArrayList();
        for (BoxManage box : exists) {
            if (StringUtils.equals(box.getPrintCode(), "1")) {
                return box.getBoxCode() + "已经使用";
            }
            boxes.add(box.getBoxCode());
        }
        int count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
        if (count > 0) {
            redisTemplate.opsForList().leftPushAll("boxs", boxes);
            redisTemplate.expire("boxs", 60, TimeUnit.SECONDS);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateRepeatPrintBox(List<BoxManage> boxManages) throws Exception {
        if (CollectionUtils.isEmpty(boxManages)) {
            return "参数不能为空！";
        }
        List<String> boxCodes = Lists.newArrayList();
        for (BoxManage boxManage : boxManages) {
            boxCodes.add(boxManage.getBoxCode());
        }
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andBoxCodeIn(boxCodes);
        List<BoxManage> exists = boxManageMapper.selectByExample(example);
        List<String> boxes = new ArrayList<>();
        for (BoxManage box : exists) {
//            if (!StringUtils.equals(box.getPrintCode(), "1")) {
//                return box.getBoxCode() + "未使用，不能复打";
//            }
            boxes.add(box.getBoxCode());
        }
        int count = boxManageMapper.batchUpdateBoxManageByCode(boxManages);
        if (count > 0) {
            redisTemplate.opsForList().leftPushAll("boxs", boxes);
            redisTemplate.expire("boxs", 60, TimeUnit.SECONDS);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public ScanCodeVo getDetailByBoxCode(ScanCodeVo scanCodeVo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String boxCode = scanCodeVo.getBoxCode();
        QueryForm queryForm = new QueryForm();
        queryForm.setBoxCode(boxCode);
        int count = boxManageMapper.selectBoxManageListCount(queryForm);
        if (count == 0) {
            scanCodeVo.setMsg("箱码不存在");
            return scanCodeVo;
        }
        //查询箱码状态
        BoxManage boxManage=boxManageMapper.selectBoxManage(boxCode);
        scanCodeVo.setStatus(boxManage.getCodeStatus());
        ProductStorageRelate relates = productStorageRelateMapper.selectByCode(boxCode);
        if (relates!=null){
            //品类
            scanCodeVo.setItemTypeId(relates.getItemTypeId());
            //规格
            scanCodeVo.setGradeValue(relates.getGradeValue());

            String str=relates.getUserName()+simpleDateFormat.format(relates.getCreateTime());
            //报工人(姓名+时间)
            scanCodeVo.setUserName(str);
            OnDutyProduct onDutyProduct=onDutyProductMapper.getById(relates.getTaskId());
            if (onDutyProduct!=null){
                //计划号
                scanCodeVo.setPlanCode(onDutyProduct.getPlanCode());
                //单件万支
                scanCodeVo.setThNumber(onDutyProduct.getThNumber());
            }
            if (onDutyProduct!=null){
                PlanOrder planOrder=planOrderMapper.getByPlanId(onDutyProduct.getPlanId());
                if (planOrder!=null){
                    OrderOutRelateExample orderOutRelateExample = new OrderOutRelateExample();
                    orderOutRelateExample.createCriteria().andOrderIdEqualTo(planOrder.getOrderId());
                    List<OrderOutRelate> orderOutRelates = orderOutRelateMapper.selectByExample(orderOutRelateExample);
                    if (orderOutRelates.size()>0){
                        for (OrderOutRelate orderOutRelate:orderOutRelates){
                            OrderOutInfoExample orderOutInfoExample = new OrderOutInfoExample();
                            orderOutInfoExample.createCriteria().andIdEqualTo(orderOutRelate.getOrderOutId());
                            orderOutInfoExample.setOrderByClause("create_time desc");
                            List<OrderOutInfo> orderOutInfos = orderOutInfoMapper.selectByExample(orderOutInfoExample);
                            if (orderOutInfos.size()>0){
                                //发货单号
                                scanCodeVo.setOrderOutCode(orderOutInfos.get(0).getOrderOutCode());
                                //客户名称
                                scanCodeVo.setCustomer(orderOutInfos.get(0).getCustomer());
                            }
                            //出库信息
                            if (orderOutInfos.size()>0){
                                ProductStorageOut productStorageOut=productStorageOutMapper.selectByRelateId(orderOutInfos.get(0).getId());
                                if (productStorageOut!=null){
                                    //出库号
                                    scanCodeVo.setStorageOutCode(productStorageOut.getStorageOutCode());
                                    //出库人
                                    scanCodeVo.setStorageOutUser(productStorageOut.getStorageOutUser());
                                    //出库时间
                                    scanCodeVo.setStorageOutTime(productStorageOut.getStorageOutTime());
                                }
                            }
                            //退货信息
                            OrderBackInfoExample orderBackInfoExample = new OrderBackInfoExample();
                            orderBackInfoExample.createCriteria().andOrderIdEqualTo(orderOutInfos.get(0).getId());
                            orderBackInfoExample.setOrderByClause("create_time desc");
                            List<OrderBackInfo> orderBackInfos = orderBackInfoMapper.selectByExample(orderBackInfoExample);
                            if (orderBackInfos.size()>0){
                                //退货号
                                scanCodeVo.setOrderBackCode(orderBackInfos.get(0).getOrderBackCode());
                                //退货人
                                scanCodeVo.setHandleUser(orderBackInfos.get(0).getHandleUser());
                                //退货时间
                                scanCodeVo.setHandleTime(orderBackInfos.get(0).getHandleTime());
                            }else {
                                scanCodeVo.setOrderBackCode("");
                                scanCodeVo.setHandleUser("");
                                scanCodeVo.setHandleTime("");
                            }
                        }
                    }
                }


            }

        }else {
            scanCodeVo.setMsg("暂无数据");
            return scanCodeVo;
        }

        return scanCodeVo;
    }

    @Override
    public List<BoxManage> getNewBoxManageList(QueryForm queryForm) throws Exception {
        //未使用
        if (queryForm.getType().equals("0")){
            int count = boxManageMapper.selectNewBoxManageListCount(queryForm);
            if (count == 0) {
                return Lists.newArrayList();
            }
            List<BoxManage> boxManages = boxManageMapper.getNewBoxManageList(queryForm);
            boxManages.get(0).setCount(count);
            return boxManages;
        } //已使用-查询最新的500条
        else if(queryForm.getType().equals("1")){
            queryForm.setPrintCode("1");
            List<BoxManage> boxManages = boxManageMapper.getNewBoxManageByUsed(queryForm);
            return boxManages;
        }//已作废-最新的100条
        else if(queryForm.getType().equals("2")){
            queryForm.setPrintCode("2");
            List<BoxManage> boxManages = boxManageMapper.getNewBoxManageByNotUsed(queryForm);
            if (boxManages.size()>0){
                boxManages.get(0).setCount(boxManages.size());
                return boxManages;
            }
        }
        return null;
    }

    @Override
    public String voidBoxManage(QueryForm queryForm) throws Exception {
        List<String> boxCodes = queryForm.getBoxCodes();
        if(CollectionsUtil.isEmpty(boxCodes)){
            throw new Exception(" boxCodes 为空！");
        }
        BoxManage boxManage = new BoxManage();
        boxManage.setPrintCode("2");
        boxManage.setVoidName(queryForm.getName());
        boxManage.setVoidTime(new Date());
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andBoxCodeIn(boxCodes);
        int count = boxManageMapper.updateByExampleSelective(boxManage,example);
        return  CommonUtil.outStr(count);
    }

    @Override
    public String batchBoxManage(QueryForm queryForm) throws Exception {
        int num = queryForm.getNum();
        if (num < 1 || num > 2000) {
            return "请输入1-2000之间的数字";
        }
        // 获取当前年份
        Calendar cal = Calendar.getInstance();
        int currentYear = cal.get(Calendar.YEAR);
        String yearSuffix = String.valueOf(currentYear).substring(2); // 获取年份后两位
        // 获取当前最大的箱码
        String maxBoxCode = boxManageMapper.selectMaxBoxCode(yearSuffix);
        long startNumber;
        if (StringUtils.isBlank(maxBoxCode)) {
            //没有任何箱码，从当前年份第一个开始
            startNumber = Long.parseLong(yearSuffix + "000001");
    } else {
            // 同一年，在最大箱码基础上+1
      startNumber = Long.parseLong(maxBoxCode) + 1;
}
        List<BoxManage> boxList = new ArrayList<>();
        List<String> boxes = Lists.newArrayList();
        for (int i = 0; i < num; i++) {
            BoxManage box = new BoxManage();
            long boxCodeValue = startNumber + i;
            String boxCodeStr = String.valueOf(boxCodeValue);
            box.setBoxCode(String.valueOf(boxCodeValue));
            box.setPrintCode("0");
            box.setCodeStatus("0");
            box.setPrintTime(queryForm.getPrintTime());
            box.setPrintUserName(queryForm.getPrintUserName());
            box.setCreateTime(new Date());
            box.setUpdateTime(new Date());
            box.setStatus("0");

            boxList.add(box);
            boxes.add(boxCodeStr);
        }
        int result = boxManageMapper.batchInsertBoxManage(boxList);

        if (result > 0) {
            String redisKey = "boxs";
            redisTemplate.delete(redisKey);
            redisTemplate.opsForList().leftPushAll(redisKey, boxes);
            redisTemplate.expire(redisKey, 60, TimeUnit.SECONDS);

            return "成功生成" + result + "个箱码";
        } else {
            return "生成箱码失败";
        }
    }

    @Override
    public BoxManageVo getBoxManageListById(QueryForm queryForm) throws Exception {
        BoxManageVo boxManageVo = new BoxManageVo();
        BoxManageExample example = new BoxManageExample();
        example.createCriteria().andBoxCodeEqualTo(queryForm.getBoxCode()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
        if (boxManages.isEmpty()) {
            throw new Exception("未找到对应的箱码信息");
        }
        String boxCode=boxManages.get(0).getBoxCode();
        boxManageVo.setBoxCode(boxCode);
        boxManageVo.setPrintCode(boxManages.get(0).getPrintCode());
        boxManageVo.setPrintTime(boxManages.get(0).getPrintTime());
        boxManageVo.setPrintUserName(boxManages.get(0).getPrintUserName());
        boxManageVo.setCodeStatus(boxManages.get(0).getCodeStatus());
        ProductStorageRelateExample relateExample = new ProductStorageRelateExample();
        relateExample.createCriteria().andBoxCodeEqualTo(boxCode);
        List<ProductStorageRelate> productStorageRelates = productStorageRelateMapper.selectByExample(relateExample);

        if (productStorageRelates.isEmpty()) {
            return boxManageVo;
        }
        ProductStorageRelate storageRelate = productStorageRelates.get(0);
        boxManageVo.setItemTypeId(storageRelate.getItemTypeId());
        boxManageVo.setGradeValue(storageRelate.getGradeValue());
        PlanManage planManage = getPlanManageById(storageRelate.getPlanId());
        if (planManage != null) {
            boxManageVo.setThNumber(planManage.getThNumber());
        }
        // 6. 查询入库信息
        ProductStorage productStorage = getProductStorageById(storageRelate.getStorageId());
        if (productStorage != null) {
            boxManageVo.setStorageCode(productStorage.getStorageCode());
            //生产入库数据
            // 机台号
            OnDutyProduct onDutyProduct = getOnDutyProductById(storageRelate.getPlanId());
            boxManageVo.setDeviceCode(onDutyProduct != null ? onDutyProduct.getDeviceCode() : "/");
            boxManageVo.setStorageType(productStorage.getStorageTypeCn()+ productStorage.getStorageStatusCn());
        }



        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 8. 设置入库人信息
        String str=simpleDateFormat.format(storageRelate.getCreateTime());
        String userName = storageRelate.getUserName()+str ;
        boxManageVo.setUserName(userName);

        //出库信息
        ProductStorageOutRelateExample productStorageOutRelateExample = new ProductStorageOutRelateExample();
        productStorageOutRelateExample.createCriteria().andBoxCodeEqualTo(boxCode);
        List<ProductStorageOutRelate> productStorageOutRelates = productStorageOutRelateMapper.selectByExample(productStorageOutRelateExample);

        if (productStorageOutRelates.size()>0){
            ProductStorageOutExample productStorageOutExample = new ProductStorageOutExample();
            productStorageOutExample.createCriteria().andIdEqualTo(productStorageOutRelates.get(0).getStroageOutId());
            List<ProductStorageOut> productStorageOuts = productStorageOutMapper.selectByExample(productStorageOutExample);
            if (productStorageOuts.size()>0){
                boxManageVo.setStorageOutCode(productStorageOuts.get(0).getStorageOutCode());
                //出库号
                if (productStorageOuts.get(0).getStorageOutType().equals("1")){
                    boxManageVo.setStorageOutType("销售");
                }else if (productStorageOuts.get(0).getStorageOutType().equals("2")){
                    boxManageVo.setStorageOutType("清理");
                }
            }
            //销售出库
            if (queryForm.getType().equals("6")){
                //订单号
                Order order = orderMapper.selectOrderById(productStorageOutRelates.get(0).getRelateId());
                boxManageVo.setOrderNum(order.getOrderNum());
                OrderOutInfoExample orderOutInfoExample = new OrderOutInfoExample();
                orderOutInfoExample.createCriteria().andIdEqualTo(productStorageOuts.get(0).getRelateId());
                List<OrderOutInfo> orderOutInfos = orderOutInfoMapper.selectByExample(orderOutInfoExample);
                //客户
                boxManageVo.setCustomer(orderOutInfos.get(0).getCustomer());
                //发货单号
                boxManageVo.setOrderOutCode(orderOutInfos.get(0).getOrderOutCode());
                //出库人
                boxManageVo.setStorageOutUser(orderOutInfos.get(0).getOutStorageUser());
                //出库时间
                boxManageVo.setStorageOutTime(orderOutInfos.get(0).getOutStorageTime());
            } else if (queryForm.getType().equals("7")){
                //客户
                boxManageVo.setCustomer("/");
                //发货单号
                boxManageVo.setOrderOutCode("/");
                //出库人
                boxManageVo.setStorageOutUser("/");
                //出库时间
                boxManageVo.setStorageOutTime("/");
            }
        }


        return boxManageVo;

    }

    @Override
    public BoxManageVo getReprintListById(QueryForm queryForm) throws Exception {
        BoxManageVo boxManageVo = new BoxManageVo();
        BoxManageExample example = new BoxManageExample();
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        statusList.add("3");
        statusList.add("4");
        statusList.add("5");
        example.createCriteria().andBoxCodeEqualTo(queryForm.getBoxCode()).andStatusEqualTo(Constants.NORMAL_STATUS).andCodeStatusIn(statusList);
        List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
        if (boxManages.isEmpty()) {
            boxManageVo.setMsg("条码无效，请输入正确条码");
            return boxManageVo;
        }
        String boxCode=boxManages.get(0).getBoxCode();
        boxManageVo.setBoxCode(boxCode);
        boxManageVo.setPrintCode(boxManages.get(0).getPrintCode());
        boxManageVo.setPrintTime(boxManages.get(0).getPrintTime());
        boxManageVo.setPrintUserName(boxManages.get(0).getPrintUserName());
        boxManageVo.setCodeStatus(boxManages.get(0).getCodeStatus());
        ProductStorageRelateExample relateExample = new ProductStorageRelateExample();
        relateExample.createCriteria().andBoxCodeEqualTo(boxCode);
        List<ProductStorageRelate> productStorageRelates = productStorageRelateMapper.selectByExample(relateExample);

        if (productStorageRelates.isEmpty()) {
            return boxManageVo;
        }
        ProductStorageRelate storageRelate = productStorageRelates.get(0);
        boxManageVo.setItemTypeId(storageRelate.getItemTypeId());
        boxManageVo.setGradeValue(storageRelate.getGradeValue());
        PlanManage planManage = getPlanManageById(storageRelate.getPlanId());
        if (planManage != null) {
            boxManageVo.setThNumber(planManage.getThNumber());
        }
        // 6. 查询入库信息
        ProductStorage productStorage = getProductStorageById(storageRelate.getStorageId());
        if (productStorage != null) {
            boxManageVo.setStorageCode(productStorage.getStorageCode());
            //生产入库数据
            // 机台号
            OnDutyProduct onDutyProduct = getOnDutyProductById(storageRelate.getPlanId());
            boxManageVo.setDeviceCode(onDutyProduct != null ? onDutyProduct.getDeviceCode() : "/");
            boxManageVo.setStorageType(productStorage.getStorageTypeCn()+ productStorage.getStorageStatusCn());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 8. 设置入库人信息
        String str=simpleDateFormat.format(storageRelate.getCreateTime());
        String userName = storageRelate.getUserName()+str ;
        boxManageVo.setUserName(userName);

        return boxManageVo;
    }

    @Override
    public BoxManageVo cleanOutbound(String boxCode) throws Exception {
        BoxManageVo boxManageVo = new BoxManageVo();
        BoxManageExample example = new BoxManageExample();
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        statusList.add("3");
        statusList.add("4");
        statusList.add("5");
        example.createCriteria().andBoxCodeEqualTo(boxCode).andStatusEqualTo(Constants.NORMAL_STATUS).andCodeStatusIn(statusList);
        List<BoxManage> boxManages = boxManageMapper.selectByExample(example);
        if (boxManages.isEmpty()) {
            boxManageVo.setMsg("条码无效，请扫描正确条码");
            return boxManageVo;
        }
        ProductStorageRelate relates = productStorageRelateMapper.selectByCode(boxCode);
        if (relates!=null){
            //品类
            boxManageVo.setItemTypeId(relates.getItemTypeId());
            //规格
            boxManageVo.setGradeValue(relates.getGradeValue());
            //规格
            boxManageVo.setBoxCode(boxCode);
        }
        return boxManageVo;
    }

    private PlanManage getPlanManageById(String planId) {
        if (planId == null) return null;
        PlanManageExample example = new PlanManageExample();
        example.createCriteria().andIdEqualTo(planId);
        List<PlanManage> result = planManageMapper.selectByExample(example);
        return result.isEmpty() ? null : result.get(0);
    }

    private ProductStorage getProductStorageById(String storageId) {
        if (storageId == null) return null;
        ProductStorageExample example = new ProductStorageExample();
        example.createCriteria().andIdEqualTo(storageId);
        List<ProductStorage> result = productStorageMapper.selectByExample(example);
        return result.isEmpty() ? null : result.get(0);
    }

    private OnDutyProduct getOnDutyProductById(String dutyProductId) {
        if (dutyProductId == null) return null;
        OnDutyProductExample example = new OnDutyProductExample();
        example.createCriteria().andPlanIdEqualTo(dutyProductId);
        List<OnDutyProduct> result = onDutyProductMapper.selectByExample(example);
        return result.isEmpty() ? null : result.get(0);
    }

//    @Scheduled(cron = "0 0 23 * * ?")
//    public void updateBoxCodes()throws Exception{
//        // 获取当前日期
//        LocalDate today = LocalDate.now();
//        // 获取当前年份
//        int currentYear = today.getYear();
//        // 获取当前年份的最后一天
//        LocalDate lastDayOfYear = LocalDate.of(currentYear, 12, 31);
//        // 判断是否是今年的最后一天
//        if (today.equals(lastDayOfYear)) {
//            this.addBoxManage(new BoxManage());
//        }
//    }

    public static void main(String args[]) {
        List<String> list1 = Lists.newArrayList();
        for (int i = 0; i < 98; i++) {
            list1.add(i + 1 + "");
        }
        for (int i = 0; i < 4; i++) {
            int startIndex = i * 25;
            int endIndex = i * 25 + 25;
            endIndex = endIndex > list1.size() ? list1.size() : endIndex;
            if (startIndex == endIndex) {
                break;
            }
            List<String> updateCodes = list1.subList(startIndex, endIndex);
            for (String str : updateCodes) {
                System.out.println(str);
            }
        }
    }
}
